package com.vinjogames.network;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.vinjogames.util.Logger;

public class WebServiceProvider {	
	private final int timeoutConnection = 3000;
	private final int timeoutSocket = 5000;
	private final String serverIP = "66.150.155.201";
	private final int port = 11962;
	private final String serviceUri = "TankMaps";

	
	public String[] getMapsFromServer(){
		String[] maps = null;
		try{
			String requestURI = String.format("http://%1$s:%2$s/%3$s", serverIP, port, serviceUri);
			String highScores = serverRequest(requestURI);
			
			JSONArray jsonArray = new JSONArray(highScores);
			maps = new String[jsonArray.length()];
					
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				//int id = (Integer)jsonObject.get("id");
				//String name = (String)jsonObject.get("name");
				String map = (String)jsonObject.get("map");
				maps[i] = map;
			}
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return maps;
	}
	
	//TODO:  highscore system?
	//       user profile info stuff?
	
	private String serverRequest(String requestURI){
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeoutConnection);
		client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, timeoutSocket);
		HttpGet httpGet = new HttpGet(requestURI);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				//Log.e(ParseJSON.class.toString(), "Failed to download file");
			}
		} catch (Exception e) {
			Logger.e(e);
		} 
		return builder.toString();
	}
}
